package com.lingyue.entity.sharding;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lingyue.entity.module.def.entity.DealershipEntity;
import com.lingyue.entity.module.def.mapper.DealershipMapper;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @version 1.0.0
 * @author: lzy
 * @date: 2019/12/17 16:39
 */
@Component
public class ShardingCacheService implements InitializingBean {
    private static final String FORMAT = "ds%d";

    @Autowired
    DealershipMapper dealershipMapper;

    @Override
    @Scheduled(cron = "0 0 8 * * *")
    public void afterPropertiesSet() throws Exception {
        Map<Long, String> map = new ConcurrentHashMap<>();
        List<DealershipEntity> dealerEntities = dealershipMapper.selectList(new QueryWrapper<DealershipEntity>());
        for (DealershipEntity entity : dealerEntities) {
            map.put(entity.getId(), String.format(FORMAT, entity.getSharding()));
        }
        CustomizedShardingAlgorithm.setDealerCache(map);
    }


}
